(defpackage :test-delimited-driver
  (:use :common-lisp :lisp-unit :abtab :abtab-delimited-driver :krb-util))

(in-package :test-delimited-driver)

(define-test test-parse-line
  (assert-equal '(nil nil nil nil nil) (->list (parse-line "" "" 5 "")))
  (assert-equal 5 (length (parse-line "" "" 5 "")))
  (assert-equal '("a" "b" "c" "d" nil)
		(->list (parse-line "," "\\" 5 "a,b,c,d,")))
  (let ((drv (make-instance 'abtab-delimited-driver
			    :delim ","
			    :escape-char "\\"
			    :columns '("C1" "C2" "C3" "C4" "C5"))))
    (assert-equal '("a" "b" "c" "d" nil)
		  (->list (parse-delimited-line drv "a,b,c,d,")))))


(define-test test-format-line
  (assert-equal "a,b,c,d," (format-line "," "\\" 5 #("a" "b" "c" "d" nil)))
  (assert-error 'record-too-long
		(format-line "," "\\" 3 #(1 2 3 4 5 6)))
  (assert-equal "a,b,c,d," (format-line "," "\\" 5 #("a" "b" "c" "d")))
  (let ((drv (make-instance 'abtab-delimited-driver
			    :delim ","
			    :escape-char "\\"
			    :columns '("C1" "C2" "C3" "C4" "C5"))))
    (assert-equal "a,b,c,d,"
		  (format-delimited-line drv '("a" "b" "c" "d")))))

(define-test test-read-block
  (let* ((col-names (cl-ppcre:split "," "ID,FIRST,MIDDLE,LAST"))
	 (tab-delimited-block
	  (string-join
	   *lf*
	   (mapcar
	    (curry #'string-join *tab*)
	    `(,col-names
	      ("1" "JOHN" "Q" "PUBLIC")
	      ("2" "JANE" "" "DOE"))))))
    (with-input-from-string (inp tab-delimited-block)
     (let ((drv (make-instance 'abtab-delimited-driver
			       :port inp
			       :uri "delim:///foo/bar.tab")))
       (reset-for-reading drv)
       (assert-equal col-names (columns drv))))))








;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun exec-tests (&optional quiet)
  "Runs the unit tests, optionally shadowing *error-output* so that
warnings (expected in some cases by the assert-error forms) do not
pollute the screen or log."
  (cond (quiet
	 (with-output-to-string (out)
	   (let ((*error-output* out))
	     (lisp-unit:run-all-tests :test-delimited-driver))))
	(t
	 (lisp-unit:run-all-tests :test-delimited-driver))))

;; (exec-tests t)
;; (use-debugger t)
;; (exec-tests)
;; (remove-all-tests nil)

;; (clear-registered-drivers)